import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_utils/src/extensions/widget_extensions.dart';
import 'package:pornhub_app/components/no_more/no_data.dart';
import 'package:pornhub_app/http/api/api.dart';
import 'package:pornhub_app/model/engagement/engagement_station_model.dart';
import 'package:pornhub_app/views/engagement/views/engagement_station_cell.dart';

class EngagementStationListPage extends StatefulWidget {
  const EngagementStationListPage({super.key});

  @override
  State createState() => _EngagementStationListPageState();
}

class _EngagementStationListPageState extends State<EngagementStationListPage> {
  late int _page = 1;
  late List<EngagementStationModel> engagementStationList = [];
  final refreshController = EasyRefreshController();

  Future<IndicatorResult> _initListData(int page) async {
    final resp = await Api.getStationList(
      page: _page,
      pageSize: 10,
    );

    if (resp == null) {
      return IndicatorResult.fail;
    }
    setState(() {
      if (page == 1) {
        engagementStationList = resp;
      } else {
        engagementStationList.addAll(resp);
      }
    });
    return IndicatorResult.success;
  }

  @override
  void initState() {
    _initListData(_page);
    super.initState();
  }

  @override
  void dispose() {
    refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.builder(
      controller: refreshController,
      childBuilder: (context, physics) {
        return ListView.builder(
          physics: physics,
          itemCount: engagementStationList.isNotEmpty
              ? engagementStationList.length
              : 1,
          itemBuilder: (context, index) {
            if (engagementStationList.isNotEmpty) {
              return EngagementStationCell(
                data: engagementStationList[index],
              );
            } else {
              return const NoData().marginOnly(top: 100.w);
            }
          },
        );
      },
      onRefresh: () async {
        _page = 1;
        return _initListData(_page);
      },
      onLoad: () async {
        _page++;
        return _initListData(_page);
      },
    );
  }
}
